package socket.socketByOIO.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * Created by yangluhua on 2017/11/7 0007.
 */
public class ServerThead extends Thread {
    private Socket socket;
    BufferedReader br = null;
    PrintStream ps = null;

    public ServerThead(Socket socket){
        this.socket = socket;
    }

    public void run(){
         try {
             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             ps = new PrintStream(socket.getOutputStream());
             String line = null;
             while ((line = br.readLine())!= null){
                 if(line.startsWith(CrazyitProtocol.USER_ROUND) && line.endsWith(CrazyitProtocol.USER_ROUND)){
                     String userName = getRealMsg(line);
                     if(OIOServer.clients.containsKey(userName)){
                         System.out.println("重复");
                         ps.println(CrazyitProtocol.NAME_REP);
                     }else {
                         System.out.println("成功");
                         ps.println(CrazyitProtocol.LOGIN_SUCCESS);
                         OIOServer.clients.put(userName,ps);
                     }
                 }else if(line.startsWith(CrazyitProtocol.PRIVATE_ROUND) && line.endsWith(CrazyitProtocol.PRIVATE_ROUND)){
                     String userAndMsg = getRealMsg(line);
                     String user = userAndMsg.split(CrazyitProtocol.SPLIT_SIGN)[0];
                     String msg = userAndMsg.split(CrazyitProtocol.SPLIT_SIGN)[1];
                     OIOServer.clients.get(user).println(OIOServer.clients.getKeyByValue(ps)+"悄悄地对你说："+msg);
                 }else {
                     String msg = getRealMsg(line);
                     for(PrintStream clientPs :OIOServer.clients.valueSet()){
                         clientPs.println(OIOServer.clients.getKeyByValue(ps)+"说："+msg);
                     }
                 }
             }
         }catch (IOException e){
             OIOServer.clients.removeValue(ps);
             System.out.println(OIOServer.clients.size());
             try {
                 if(br != null){
                     br.close();
                 }
                 if(ps != null){
                     ps.close();
                 }
                 if(socket != null){
                     socket.close();
                 }
             }catch (IOException ex){
                 ex.printStackTrace();
             }
         }
    }

    private String getRealMsg(String line){
        return line.substring(CrazyitProtocol.PROTOCAL_LEN,line.length() - CrazyitProtocol.PROTOCAL_LEN);
    }
}
